# -*- coding:utf-8 -*-

from flask import request
from . import userbp
from app.utils.MySQLClient import MySQLClinet as mmysql
from app.utils.RedisClient import RedisClinet as rredis
import uuid

@userbp.route('/123')
def start_running():
    return "程序启动"

@userbp.route('/login',methods=['post'])
def user_login():
    userName = request.json.get('username')
    passWord = request.json.get('password')

    sql = "select * from tb_user where username='{}' and password='{}' and status=1".format(userName, passWord)
    result = mmysql().query(sql)

    if len(result) == 0:
        data = return_msg(0,"登录失败!")
    else:
        # 生成token
        token = str(uuid.uuid4())
        rredis().hset_value("user_tokens",f"{userName}_token",token)
        t_data = [{"token":token},]
        data = return_msg(1,"登录成功!",t_data)
    return data

@userbp.route('/reg',methods=['post'])
def user_reg():
    userName = request.json.get('username')
    passWord = request.json.get('password')
    age = request.json.get('age')
    gender = request.json.get('gender')

    sql = "select * from tb_user where username='{}'".format(userName)
    result = mmysql().query(sql)
    if len(result) > 0:
        data = return_msg(0,"注册失败，账号已存在!")
        return data

    sql = "INSERT INTO tb_user VALUES (null,'{}','{}','{}','{}','1')".format(userName,passWord,age,gender)
    db_res = mmysql().commit(sql)
    if db_res:
        data = return_msg(1,"注册成功")
    else:
        data = return_msg(0,"注册失败")
    return data

@userbp.route('/token',methods=['post'])
def tokenCheck():
    token = request.headers.get("token")

    tokens = rredis().hget_all("user_tokens")
    for t in tokens.values():
        res_key = str(t, encoding="utf-8")
        if res_key == token:
            return return_msg(1,"检查成功！")
    return return_msg(0,"检查失败！")

@userbp.route('/upload',methods=['post'])
def upload():
    file = request.files['file']
    file.save('./'+file.filename)
    return return_msg()

def return_msg(code=1, msg="操作成功", data=[]):
    return {"code":code, "msg":msg, "data":data}